package com.sihan.framework.etm.service.impl;

import java.lang.reflect.Method;
import java.util.Set;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;

import com.sihan.framework.etm.common.CacheOperatorInfo;
import com.sihan.framework.etm.common.util.EtmWebUtil;
import com.sihan.framework.etm.enums.CacheKeyName;
import com.sihan.framework.etm.service.OperatorService;
import com.sihan.framework.etm.service.RoleService;

import lombok.extern.slf4j.Slf4j;

@Component
@Slf4j
public class OperatorServiceImpl implements OperatorService {

    @Autowired
    private RoleService roleService;

    @Override
    public Boolean validate(Object handler) {
        Boolean hasPermition = false;
        String[] permitions = null;
        try {
            permitions = this.parseAnnotation(handler);
            if (null == permitions || permitions.length == 0) {
                return true;
            }
        } catch (Exception e) {
            log.error("验证权限失败", e);
        }
        String userId = (String) CacheOperatorInfo.getMapValue(CacheKeyName.VALIDATED_USER_ID.getValue(), null);
        if (StringUtils.isBlank(userId)) {
            userId = EtmWebUtil.userId();
        }
        if (!StringUtils.isBlank(userId)) {
            try {
                Set<String> roles = roleService.selectPermissionByUserId(userId);
                if (null == roles || roles.isEmpty()) {
                    return false;
                }
                for (String role : roles) {
                    for (String p : permitions) {
                        if (p.equals(role)) {
                            hasPermition = true;
                            break;
                        }
                    }
                }
            } catch (Exception e) {
                log.error("验证权限失败", e);
            }
        }
        return hasPermition;
    }

    /**
     * @param handler
     * @return
     * @return String[]
     * @throws ClassNotFoundException
     * @description 验证是否有权限的限制
     * @auther 韩兵
     * @Date 2020年9月21日
     */
    private String[] parseAnnotation(Object handler) throws ClassNotFoundException {
        if (!(handler instanceof HandlerMethod)) {
            return null;
        }
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        Method method = handlerMethod.getMethod();
        if (null == method.getAnnotation(RequiresPermissions.class)) {
            return null;
        }
        String[] values = method.getAnnotation(RequiresPermissions.class).value();
        return values;
    }

}
